package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Override
    public ResponseResult login(WmUserDto dto) {
        //1.参数校验
        if(dto==null|| StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            //三者任一为空则返回参数异常
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser one = getOne(Wrappers.<WmUser>lambdaQuery()
                .eq(WmUser::getName, dto.getName())
                .eq(WmUser::getStatus, AdminConstants.USER_STATUS_EXIT));
        if (one==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NUMBER_DOTEXIT_OR_CLOSURE);
        }
        //2.数据加密对比
        String pwd=dto.getPassword()+one.getSalt();
        String s = DigestUtils.md5DigestAsHex(pwd.getBytes());
        if(!s.equals(one.getPassword())){
            //两个结果不相等话返回账号或者密码错误
            System.out.println("账号或者密码错误");
//            CustException.cust(AppHttpCodeEnum.NUMBER_DOTEXIT_OR_CLOSURE);
            return ResponseResult.errorResult(AppHttpCodeEnum.NUMBER_DOTEXIT_OR_CLOSURE);
        }
        //3.校验成功,刷新这个登录时间
        one.setLoginTime(new Date());
        updateById(one);
        //4.制造token并返回给前端
        String token = AppJwtUtil.getToken(one.getId().longValue());
        HashMap<Object, Object> map = new HashMap<>();
        map.put("token",token);
        one.setSalt(null);
        one.setPassword(null);
        one.setEmail(null);
        one.setPhone(null);
        map.put("user",one);
        //5.返回结果封装回前端
        return ResponseResult.okResult(map);
    }
}
